package com.piece.admin.config;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.piece.core.framework.constant.CookieConstants;
import com.piece.core.framework.properties.ApplicationProperties;
import com.piece.core.web.authority.AuthorityFactory;
import com.piece.core.web.config.WebMvcAutoConfig;
import com.piece.core.web.interceptor.ContextInterceptor;
import com.piece.core.web.properties.SecurityProperties;
import com.piece.core.web.resolver.TokenArgumentResolver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import javax.annotation.Resource;
import java.io.File;
import java.util.*;

@Slf4j
@Configuration
@Import(WebMvcAutoConfig.class)
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Autowired
    private ApplicationProperties applicationProperties;

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private FastJsonHttpMessageConverter fastJsonHttpMessageConverter;

    @Autowired
    private ContextInterceptor contextInterceptor;

    @Autowired
    private LocaleChangeInterceptor localeChangeInterceptor;

    @Resource
    private AuthorityFactory authorityFactory;

    /**
     * 默认首页的设置，输入域名自动跳转到默认指定的网页
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/api/index");
    }

    // 添加转换器
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(fastJsonHttpMessageConverter);
    }

    @Bean
    public LocaleResolver localeResolver() {
        CookieLocaleResolver localeResolver = new CookieLocaleResolver();
        localeResolver.setCookieName(CookieConstants.LANGUAGE);
        localeResolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
        localeResolver.setCookieMaxAge(3600);
        return localeResolver;
    }

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        List<String> interceptors = new ArrayList<>();
        for (String endpoint : authorityFactory.ENDPOINTS) {
            interceptors.add(endpoint);
        }
        interceptors.add("/" + applicationProperties.getUpload() + "/**");

        registry.addInterceptor(contextInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(interceptors);
        registry.addInterceptor(localeChangeInterceptor);
    }

    /**
     * Token参数解析
     */
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        //注入用户信息
        argumentResolvers.add(new TokenArgumentResolver());
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /** 静态资源路径配置 */
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/META-INF/resources/");
        /** webjars配置 */
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        /** swagger配置 */
        registry.addResourceHandler("/swagger-ui.html", "/swagger-ui/index.html", "/doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        try {
            // 项目根目录
            Properties props = System.getProperties();
            String rootPath = props.getProperty("user.dir");
            String uploadResource = "/" + applicationProperties.getUpload() +"/**";
            File desc = new File(rootPath);
            //临时文件目录
            String dir = desc.getPath() + File.separator + applicationProperties.getUpload() + File.separator + "temp";
            desc = new File(dir);
            if (!desc.exists()) {
                desc.mkdirs();
            }
            //文件目录
            dir = desc.getPath() + File.separator + applicationProperties.getUpload();
            desc = new File(dir);
            if (!desc.exists()) {
                desc.mkdirs();
            }
            /** 上传附件配置 */
            registry.addResourceHandler(uploadResource).addResourceLocations("file:" + dir);
        } catch (Exception e) {
            log.error("附件文件路径异常：{}", e.getMessage());
        }
    }

    //@Bean
    public CorsFilter corsFilter() {
        // 创建 CorsConfiguration 对象
        CorsConfiguration config = new CorsConfiguration();
        // 允许凭证
        config.setAllowCredentials(true);
        // 允许任何来源
        config.addAllowedOriginPattern(CorsConfiguration.ALL);
        //config.setAllowedOriginPatterns(Collections.singletonList("*"));
        // 允许任何请求头
        config.addAllowedHeader(CorsConfiguration.ALL);
        // 允许任何方法
        config.addAllowedMethod(CorsConfiguration.ALL);
        // 暴露的头部信息
        config.addExposedHeader(CorsConfiguration.ALL);
        // 创建 UrlBasedCorsConfigurationSource 对象
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config); // 对接口配置跨域设置
        return new CorsFilter(source);
    }

    @Override
    protected void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns(CorsConfiguration.ALL)
                .allowedHeaders(CorsConfiguration.ALL)
                .allowedMethods(CorsConfiguration.ALL)
                .allowCredentials(true)
                .maxAge(3600);
    }
}
